<template>
  <section class="card">
    <header class="card-header">
      <div class="title">考试情况</div>
      <div class="ops">
        <el-input v-model="query.keyword" placeholder="按姓名或试卷搜索" size="small" style="width: 220px"
          @keyup.enter="loadList" />
        <el-button size="small" @click="loadList">查询</el-button>
        <el-button size="small" class="secondary" @click="resetQuery">重置</el-button>
      </div>
    </header>
    <div class="card-body">
      <el-table :data="list" border stripe v-loading="loading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="考试姓名" min-width="140">
          <template #default="{ row }">
            {{ row?.sysUser?.account ?? row?.sysUser?.nickname ?? '-' }}
          </template>
        </el-table-column>
        <el-table-column label="试卷名称" min-width="180">
          <template #default="{ row }">
            {{ row?.examPaper?.name ?? `试卷#${row?.paperId}` }}
          </template>
        </el-table-column>
        <el-table-column prop="totalScore" label="考试分数" width="120">
          <template #default="{ row }">{{ row?.totalScore ?? '-' }}</template>
        </el-table-column>
        <el-table-column label="答题状态" width="120">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row?.status)">{{ statusText(row?.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" min-width="180">
          <template #default="{ row }">{{ formatTime(row?.startTime) }}</template>
        </el-table-column>
        <el-table-column label="提交时间" min-width="180">
          <template #default="{ row }">{{ formatTime(row?.submitTime) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="160">
          <template #default="{ row }">
            <el-button size="small" @click="viewAttempt(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pager">
        <el-pagination background layout="prev, pager, next" :page-size="query.size" :current-page="query.page"
          :total="total" @current-change="handlePage" />
      </div>
    </div>
  </section>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { pageUserAttempts } from '@/api/exam/exam'

const router = useRouter()

const list = ref<any[]>([])
const loading = ref(false)
const total = ref(0)
const query = reactive({ keyword: '', page: 1, size: 10 })

function statusText(s?: number) {
  if (s === 2) return '已提交'
  if (s === 1) return '考试中'
  return '未知'
}
function statusTagType(s?: number) {
  if (s === 2) return 'success'
  if (s === 1) return 'warning'
  return 'info'
}
function formatTime(t?: string) {
  if (!t) return '-'
  try {
    return new Date(t).toLocaleString()
  } catch {
    return t
  }
}

async function loadList() {
  loading.value = true
  try {
    const res = await pageUserAttempts({ page: query.page, size: query.size, keyword: query.keyword })
    const raw = res?.data?.data ?? res?.data
    if (Array.isArray(raw)) {
      list.value = raw
      total.value = raw.length
    } else {
      list.value = raw?.list ?? []
      total.value = raw?.total ?? 0
      if (raw?.pageNum != null || raw?.page != null) query.page = raw.pageNum ?? raw.page
      if (raw?.pageSize != null || raw?.size != null) query.size = raw.pageSize ?? raw.size
    }
  } catch (e) {
    ElMessage.error('加载考试记录失败')
  } finally {
    loading.value = false
  }
}

function handlePage(p: number) {
  query.page = p
  loadList()
}

function resetQuery() {
  query.keyword = ''
  query.page = 1
  loadList()
}

function viewAttempt(row: any) {
  const id = row?.id
  if (!id) {
    ElMessage.error('无法打开详情：缺少记录ID')
    return
  }
  const resolved = router.resolve({ path: `/examAttempt/${id}` })
  window.open(resolved.href, '_blank')
}

onMounted(loadList)
</script>

<style scoped>
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 6px 12px 6px;
  border-bottom: 1px solid #f0f0f0;
}

.card-header .title {
  font-weight: 600;
}

.card-header .ops {
  display: flex;
  gap: 8px;
  align-items: center;
}

.card-body {
  padding-top: 12px;
}

.pager {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
</style>
